package com.aurora.source.util;

import android.text.TextUtils;

import com.aurora.source.constant.AuroraConstants;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author: Lance
 * @description: String 工具类
 * @date: 2018/7/6 14:010
 */
public class StringUtils {
    /**
     * @param stringList
     * @return 把stringList变成逗号分隔的String
     */
    public static String getStringFromList(List<String> stringList) {
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < stringList.size(); i++) {
            if (i < stringList.size() - 1) {
                stringBuilder.append(stringList.get(i) + ",");
            } else {
                stringBuilder.append(stringList.get(i));
            }
        }
        return stringBuilder.toString();
    }

    //根据key进行字母排序
    public static String sortValueByKey(Map<String, String> stringMap) {
        if (stringMap == null) {
            return null;
        }
        StringBuilder builder = new StringBuilder();
        try {
            Map<String, String> sortMap = new TreeMap<>(new MapKeyComparator());
            sortMap.putAll(stringMap);
            String sortKey = "";
            String sortValue = "";
            for (Map.Entry<String, String> entry : sortMap.entrySet()) {
                if (!isChineseChar(entry.getValue())) { //有中文的参数不校验
                    builder.append(entry.getValue());
                    sortKey += entry.getKey() + "\n";
                    sortValue += entry.getValue() + "\n";
                }
            }
            LogUtils.i("sortKey:" + sortKey);
            LogUtils.i("sortValue:" + sortValue);
            builder.append(AuroraConstants.SIGN_KEY_VALUE);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return builder.toString();
    }

    // 比较器
    static class MapKeyComparator implements Comparator<String> {
        @Override
        public int compare(String str1, String str2) {
            return str1.compareTo(str2);
        }
    }

    /**
     * 检测字符串中是否包含中文字符
     */
    public static boolean isChineseChar(String text) {
        boolean temp = false;
        try {
            Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
            Matcher m = p.matcher(text);
            if (m.find()) {
                temp = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return temp;
    }
}
